//========================================================================
// FILENAME : util.c
// CREATED : 07-03-2009
// AUTHOR : Jesper Aagaard Vuholm
// DESCR. : This file is used to hold things that wont fit elsewhere,
//          to keep our code clean.
//
//------------------------------------------------------------------------
//
// REV. DATE/AUTHOR CHANGE DESCRIPTION
// 1.00 07-03-2009/Jesper function ***create_checksum*** added.
// 1.01 21-04-2009/Jesper function ***is_a_number*** added.
// 1.02 09-05-2009/Jesper function ***BEEP*** added.
//========================================================================
#include "Utils.h"

#define sbi(port,pin)    port |= 1<<pin    //set bit
#define cbi(port,pin)    port &= ~(1<<pin) //clear bit

//=============================================================
// METHOD : unsigned int create_checksum( char data_arr[] )
// DESCR. : Calculate a simple checksum, and return the result.
//=============================================================
unsigned int create_checksum( char data_arr[] )
{
	unsigned char i = 0;
	unsigned int crc_sum = 0;
	while(data_arr[i]!= '$')
	{
		crc_sum += data_arr[i];
		i++;
	}
	return crc_sum;
}

//=============================================================
// METHOD : unsigned char is_a_number(char x)
// DESCR. : Returns 1 if x is a number, and 0 if not.
//          Apparently gcc had trouble understanding
//          range check on char, even if casted to unsigned chars,
//          therefore this "ugly" check function.
//=============================================================
unsigned char is_a_number(char x)
{
	if(x == '0' || x == '1' || x == '2' || x == '3' || x == '4' ||
	   x == '5' || x == '6' || x == '7' || x == '8' || x == '9')
		return 1;
	else
		return 0;
}

//=============================================================
// METHOD : void BEEP(unsigned int beepLenght)
// DESCR. : Makes 4 beeps, where the sound length is decided
//          by beepLenght.
//=============================================================
void BEEP(unsigned int beepLenght)
{
	DDRB = 0b11111111;
	PORTB = 0b11111111;

	for(int i = 0; i < 4; i++)
	{
		cbi(PORTB,PIN1);
		sbi(PORTB,PIN0);
		_delay_ms(beepLenght);
		sbi(PORTB,PIN1);
		cbi(PORTB,PIN0);
		_delay_ms(20);
	}
	cbi(PORTB,PIN1);
	//Stop beep
	cbi(PORTB,PIN0);
}
